package org.wangnian.demo02_config_file.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

import java.io.IOException;
import java.util.Properties;

public class CustomPropertySourceFactory extends DefaultPropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        try {
            String filename = resource.getResource().getFilename();
            if (filename.endsWith(".yml") || filename.endsWith(".yaml")){
                YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
                factoryBean.setResources(resource.getResource());
                Properties properties = factoryBean.getObject();
                return new PropertiesPropertySource(filename,properties);
            }
        } catch (Exception e) {
            return super.createPropertySource(name, resource);
        }
        return super.createPropertySource(name, resource);
    }
}
